package com.qk.management.web.interceptor;

import com.qk.common.util.CurrentUserContextHolders;
import com.qk.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

/**
 * @author: Enid
 * @date: 2025/10/11 14:53
 * @description: 登录校验的拦截器
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    private static final String TOKEN_HEADER_NAME = "token";
    /**
     * 在到达控制前 拦截请求
     * 登录校验
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 处理器 本质就是controller中的方法 所代之的对象
     * @return  true 放行 false不放行
     * @throws Exception 抛出的异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader(TOKEN_HEADER_NAME);

        if (Objects.isNull(token)){
            log.info("token为空");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

        try {
            Claims claims = JwtUtil.parseToken(token);
            String username = claims.get("username", String.class);
            log.info("================用户名：{}=================",username);
            Integer id =claims.get("id", Integer.class);
            log.info("================用户id：{}=================",id);
            CurrentUserContextHolders.set(id);
            return true;
        } catch (Exception e) {
            log.error("token解析失败");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentUserContextHolders.remove();
    }
}
